package com.zhaoxi.demo;

import com.zhaoxi.demo.domain.UserEx;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.Date;
import java.util.List;

/**
 * Created by Infor on 2017/07/15.
 */
public class AnnotationTest {

    static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    public static void main(String[] args) {
        userExTest();
    }

    private static void userExTest(){
        // 新增
        UserEx user = new UserEx();
        user.setName("张三");
        user.setAge(20);
        user.setPhone(13512345678L);
        user.setCreateDate(new Date());
        user.setState(true);

        add(user);
        query("张三");
        user.setPhone(18888888888L);
        update(user);
        query("张三");
        delete(user.getId());
    }

    private static void add(UserEx user) {
        Session session = sessionFactory.openSession();
        try {
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    private static void update(UserEx user) {
        Session session = sessionFactory.openSession();
        try {
            session.beginTransaction();
            session.update(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    private static void query(String name) {
        Session session = sessionFactory.openSession();
        Query query = session.createQuery("from UserEx where name=?");
        query.setParameter(0, name);
        List<UserEx> users = query.list();

        for (UserEx user : users) {
            System.out.println(user);
        }
        session.close();
    }

    private static void delete(int id) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        UserEx user = new UserEx();
        user.setId(id);
        session.delete(user);
        session.getTransaction().commit();
        session.close();
        System.out.println("delete id :" + id);
    }

}
